package com.shujia.wyh.day28;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
        服务器端程序编写
            1、创建服务器端的ServerSocket对象
            2、监听客户端的连接
            3、获取通道中字节输入流对象
            4、创建字符输出流对象（由于是本地模拟，为了防止文件名冲突，我就以时间戳命名）
            5、向文件中写入数据
            6、获取通道中的字节输出流对象，给客户端一个反馈
            7、释放资源
 */
public class UploadServer {
    public static void main(String[] args) throws Exception {
        //创建服务器端的ServerSocket对象
        ServerSocket ss = new ServerSocket(12345);

        //监听客户端的连接
        Socket s = ss.accept();

        //获取通道中字节输入流对象
        BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));

        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
        String format = sdf.format(date);
        //创建字符输出流对象
        BufferedWriter bw = new BufferedWriter(new FileWriter(format + ".txt"));
//        BufferedWriter bw = new BufferedWriter(new FileWriter(System.currentTimeMillis() + ".txt"));

        String line = null;
        while ((line=br.readLine())!=null){
            bw.write(line);
            bw.newLine();
            bw.flush();
        }

        //向客户端写一个反馈
        BufferedWriter bw2 = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        bw2.write("文件上传成功！");
        bw2.newLine();
        bw2.flush();

        //释放资源
        bw.close();
        s.close();

    }
}






